<?php
require_once __DIR__ . '/../vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
use Medoo\Medoo; 

$connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
$channel = $connection->channel();
$channel->queue_declare('gp_5day', false, false, false, false);
echo " [*] Waiting for messages. To exit press CTRL+C\n";
$callback = function ($msg) {
    echo ' [x] Received ', $msg->body, "\n";
    $database = new Medoo([
        'database_type' => 'mysql',
        'database_name' => 'gp',
        'server'        => '127.0.0.1',
        'username'      => 'root',
        'password'      => '0263d88b9e241e09'
    ]);

    $msg_data = json_decode($msg->body, true);
    $url = 'https://gupiao.baidu.com/api/stocks/stocktimelinefive?from=pc&os_ver=1&cuid=xxx&vv=100&format=json&stock_code='.$msg_data['f_code'].'&step=3&timestamp=' . time();
    $get_res = _curl_get($url);
    $get_res = json_decode($get_res, true);
    if ( ! $get_res) {
        return;
    }
    if ($get_res['timeLine']) {
        foreach ($get_res['timeLine'] as $k => $v) {
            $time_info = $database->select('t_price_5day', ['id'], ['f_code' => $msg_data['f_code'], 'date' => $v['date'], 'time' => $v['time']]); 
            if (empty($time_info)) {
                $time_data = [
                    'f_code' => $msg_data['f_code'],
                    'amount'   => $v['amount'],
                    'avgPrice' => $v['avgPrice'],
                    'ccl'      => $v['ccl'],
                    'date'     => $v['date'],
                    'netChangeRatio' => $v['netChangeRatio'],
                    'preClose'       => $v['preClose'],
                    'price'          => $v['price'],
                    'time'           => $v['time'],
                    'volume'         => $v['volume']
                ];
                $database->insert('t_price_5day', $time_data);
            }
        }
    }
};
$channel->basic_consume('gp_5day', '', false, true, false, false, $callback);
while (count($channel->callbacks)) {
    $channel->wait();
}
$channel->close();
$connection->close();

function _curl_get($url)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_TIMEOUT, 1);
    $data = curl_exec($curl);
    curl_close($curl);
    return $data;
}
